class Compiler {
    event = {};
    constructor(vm){
        this.el = vm.$el;
        this.vm = vm;
        this.compile(this.el);
    }
    // 编译模板，处理文本节点和元素节点
    compile(el){
        const nodes = Array.from(el.childNodes);
        nodes.forEach(node => {
           if(this.isTextNode(node)){
               this.compileText(node);
           }else if(this.isElementNode(node)){
               this.compileElement(node);
           }
           // 判断node节点是否有子节点，如果有则要递归调用
           if(node.childNodes && node.childNodes.length){
               this.compile(node);
           }
        });
    }
    // 编译元素节点，处理指令
    compileElement(node){
        const attrs = Array.from(node.attributes);
        attrs.forEach(attr => {
            let attrName = attr.name;
           if(this.isDirective(attrName)){
               attrName = attrName.substring(2);
               let key = attr.value;
               if(attrName.startsWith('on:')){
                   this.eventBind(node,key,attrName)
               }else{
                   this.update(node,key,attrName);
               }
           }
        });
    }
    update(node,key,attrName){
        const fn = this[attrName + 'Updater'];
        console.log(attrName,key);
        fn && fn.call(this,node, key,this.vm[key]);
    }
    // 处理v-text
    textUpdater(node, key,value) {
        node.textContent = value;
        new Watch(this.vm, key, (newValue) => {
            node.textContent = newValue;
        })
    }
    // 处理v-model
    modelUpdater(node,key,value){
        node.value = value;
        new Watch(this.vm, key, (newValue) => {
            node.value = newValue;
        });
        // 双向绑定
        node.addEventListener('input',() => {
            this.vm[key] = node.value;
        })
    }
    // 作业：v-html
    htmlUpdater(node,key,value) {
        node.innerHTML = value;
        new Watch(this.vm, key, (newValue) => {
            node.innerHTML = newValue;
        });
    }
    // 作业：v-on 处理事件
    eventBind(node,key,attrName){
        let eventType = attrName.split(':')[1];
        let callback = this.vm.$options.methods[key];
        if(callback){
            node.addEventListener(eventType,callback.bind(this.vm));
        }
    }
    // 处理文本节点，转换插值表达式
    compileText(node){
        const text = node.textContent;
        const reg = /\{\{(.+?)\}\}/;
        if(reg.test(text)){
            const key = RegExp.$1.trim();
            node.textContent = text.replace(reg,this.vm[key]);

            new Watch(this.vm,key,(newValue) => {
                node.textContent = text.replace(reg,newValue);
            });
        }
    }
    // 判断是否是指令
    isDirective(attrName){
        return attrName.startsWith('v-');
    }
    // 判断是否是文本节点
    isTextNode(node){
        return node.nodeType === 3;
    }
    // 判断是否是元素节点
    isElementNode(node){
        return node.nodeType === 1;
    }
}
